package com.itheima.controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cookie")
public class TestCookieController {

    /**
     * 存cookie
     * @param response
     * @return
     */
    @GetMapping("save")
    public Result saveCookie(HttpServletResponse response){
        Cookie cookie = new Cookie("username","孙铭");
        response.addCookie(cookie);
        Cookie cookie1 = new Cookie("password","123456");
        response.addCookie(cookie1);
        return Result.success();
    }

    /**
     * 获取cookie
     */
    @GetMapping("get")
    public Result getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        JSONObject result = new JSONObject();
        for (Cookie cookie : cookies) {
            result.put(cookie.getName(), cookie.getValue());
        }
        return Result.success(result);
    }

}
